using System;
using System.Threading;

namespace Catastrophe.Common.ThreadLock
{
	public sealed class HslAsyncCoordinator
	{
		private int OperaterStatus = 0;

		private long Target = 0L;

		private Action action = null;

		public HslAsyncCoordinator(Action operater)
		{
			this.action = operater;
		}

		public void StartOperaterInfomation()
		{
			Interlocked.Increment(ref this.Target);
			if (Interlocked.CompareExchange(ref this.OperaterStatus, 1, 0) == 0)
			{
				ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadPoolOperater), null);
			}
		}

		private void ThreadPoolOperater(object obj)
		{
			long num = this.Target;
			long num2 = 0L;
			long num3;
			do
			{
				num3 = num;
				this.action?.Invoke();
				num = Interlocked.CompareExchange(ref this.Target, num2, num3);
			}
			while (num3 != num);
			Interlocked.Exchange(ref this.OperaterStatus, 0);
			if (this.Target != num2)
			{
				this.StartOperaterInfomation();
			}
		}
	}
}
